﻿using System;
using GameX.GameContent;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GameX.MapEngine
{
    class Map : IDrawableMap
    {
        private Tile[,] m_tiles;
        private ISpriteSheet m_spriteSheet;

        public Map(uint width, uint height, ISpriteSheet spriteSheet)
        {
            if (spriteSheet == null)
            {
                throw new ArgumentNullException("spriteSheet");
            }

            m_tiles = new Tile[width, height];
            m_spriteSheet = spriteSheet;
        }

        public void SetTileAt(uint x, uint y, Tile tile)
        {
            m_tiles[x, y] = tile;
        }

        public void Draw(GraphicsDevice graphics)
        {
            if (graphics == null)
            {
                throw new ArgumentNullException("graphics");
            }

            var spriteBatch = new SpriteBatch(graphics);

            spriteBatch.Begin();

            for (int x = 0; x < m_tiles.GetLength(0); x++)
            {
                for (int y = 0; y < m_tiles.GetLength(1); y++)
                {
                    Tile currentTile = m_tiles[x, y];

                    uint tileType = (uint)currentTile.TileType;

                    Rectangle spriteBounds = m_spriteSheet.GetSpriteBounds(tileType);

                    int offsetX = y % 2 == 0 ? m_spriteSheet.GetTileWidth(tileType) / 2 : 0;

                    var mapDestination = new Rectangle(
                        x * m_spriteSheet.GetTileWidth(tileType) + offsetX,
                        y * m_spriteSheet.GetTileHeight(tileType) - (y * m_spriteSheet.GetTileHeight(tileType) * 3 / 4),
                        m_spriteSheet.GetTileWidth(tileType),
                        m_spriteSheet.GetTileHeight(tileType));

                    spriteBatch.Draw(m_spriteSheet.Texture, mapDestination, spriteBounds, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1);
                }
            }

            spriteBatch.End();
        }
    }
}
